import { showAlert } from "../functionFromexport.js";

const WebApp = window.Telegram.WebApp;

WebApp.BackButton.show();

WebApp.onEvent("backButtonClicked", function () {
  history.back();
  WebApp.BackButton.hide();
});

const sendButton = document.getElementById("sendButton");
const nameClientField = document.getElementById("nameClient");

// let numberFromTg = "+79099142529";

//let chatId = WebApp.initDataUnsafe.user.id;
let chatId = "456072370";
const inputNumber = document.getElementById("numberFromTg");

fetch("/client", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    chatId: chatId,
  }),
})
  .then((response) => response.json())
  .then((data) => {
    // console.log(data);
    displayClientPhone(data);
  })
  .catch((err) => {
    console.log(err);
  });

const displayClientPhone = (client) => {
  client.forEach(({ tg_phone_plus }) => {
    inputNumber.value = tg_phone_plus;
  });
};

const innerErrMessage = document.getElementById("errMess");

nameClientField.addEventListener("focus", () => {
  innerErrMessage.innerText = "";
  nameClientField.style.border = "none";
});

sendButton.addEventListener("click", (e) => {
  e.preventDefault();
  if (nameClientField.value < 1) {
    innerErrMessage.innerText = "Введите имя";
    nameClientField.style.border = "1px solid red";
    return;
  }
  fetch("/newclient", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      name: nameClientField.value,
      phone: inputNumber.value,
    }),
  })
    .then((res) => res.json())
    .then((data) => {
      // console.log(data);
      console.log(data.success);
      if (data.success) {
        showAlert("Ваши данные отправленны");
        setTimeout(() => {
          window.location.href = "/";
        }, 2500);
      }
      if (
        data.meta.message ==
        "Клиент с указанным телефоном уже существует в базе"
      ) {
        showAlert("Вы уже зарегистрированы, авторизуйтесь");
        setTimeout(() => {
          window.location.href = "/";
        }, 2500);
      }
    })
    .catch((err) => {
      console.log(err);
    });
});
